<template>
  <div class="search-container">
    <!-- 顶部栏 -->
    <van-nav-bar title="搜索中心" left-arrow @click-left="$router.go(-1)" />
    <!-- 搜索栏 -->
    <van-search
      v-model="value"
      show-action
      shape="round"
      autofocus
      placeholder="请输入搜索关键词"
      @search="onSearch"
      @input="onInput"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    <!-- 搜索列表 -->
    <van-cell-group>
      <van-cell v-for="(item, index) in showList" :key="index" icon="search"
      @click="$router.push({path:'/searchResult',query:{q:suggestionList[index]}})"
      >
        <template #title>
          <span class="custom-title" v-html="item"></span>
        </template>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { getSuggestion } from './home.js'
export default {
  name: 'search',
  data () {
    return {
      value: '', //搜索内容
      suggestionList: [], // 推荐词列表
      timeID:null,//函数防抖定时器
    }
  },
  methods: {
    /* 搜索事件:输入框回车 + 点击右侧搜索按钮 */
    onSearch () {
      console.log('搜索' + this.value)
      // 跳转搜索结果页并传参
      this.$router.push({path:'/searchResult',query:{q:this.value}})
    },
    /* 输入事件:输入框内容变化 */
    onInput () {
      /* 防抖第一步:先清除上一次定时器，以最后一次为准 */
      clearTimeout(this.timeID)
      /* 防抖第二步:开启防抖定时器 */
      this.timeID = setTimeout( async ()=>{
        console.log('输入' + this.value)
        // 0.非空判断
        if (this.value == '') {
          this.suggestionList = []
          return
        }
        // 1.获取推荐词列表
        let res = await getSuggestion(this.value)
        console.log(res)
        // 2.绑定数据
        this.suggestionList = res.data.data.options
      },500)
    }
  },
  computed: {
    showList () {
      // map:遍历数组，根据某种映射规则生成一个新数组
      // 这个return 返回计算属性值
      return this.suggestionList.map(value => {
        let reg = new RegExp(this.value, 'ig')
        // 这个return返回map映射结果(新数组的元素值)
        return value.replace(
          reg,
          match => `<span style="color:red">${match}</span>`
        )
      })
    }
  }
}
</script>

<style lang="less">
.search-container {
  .van-nav-bar__content {
    background-color: #008bfa;
    .van-nav-bar__title {
      color: #fff;
    }
    .van-icon {
      color: #fff;
    }
  }
}
</style>
